package com.fy.service.server.listener;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;

@Component
public class NacosListener implements ApplicationRunner {

	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Value("${spring.cloud.nacos.config.server-addr}")
	private String serverAddr ;
	
	@Value("${spring.application.name}")
	private String serverName ;
	
	

	@Autowired
    private DiscoveryClient discoveryClient;

	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		// TODO Auto-generated method stub
		NamingService createNamingService = NacosFactory.createNamingService(serverAddr);
		createNamingService.subscribe(serverName,new EventListener() {
			
			@Override
			public void onEvent(Event event) {
				// TODO Auto-generated method stub
				System.out.println("-------AUTH-----------serverAddr:"+serverAddr);
				
				logger.info(" come in onEvent:{}",serverName);
				
				 
			     if(event instanceof NamingEvent){
			    	 System.out.println(" instance event"+JSON.toJSONString(event));
			    	 
			    	 System.out.println(" ServiceName: "+((NamingEvent)event).getServiceName());
				     System.out.println(" instance: "+((NamingEvent)event).getInstances());
				     
				     List<Instance> instances = ((NamingEvent)event).getInstances();
				     for (Instance instance : instances) {
				    	 
						System.out.println(" instance: "+JSON.toJSONString(instance));
						System.out.println(" instance: "+instance.getIp());
						System.out.println(" ip: "+instance.getPort());
						
						
					}
			     }
			     
			     
			     
			}
		});
		
		
		List<ServiceInstance> instances = discoveryClient.getInstances(serverName);
		for (ServiceInstance instance : instances) {
			System.out.println(" instance: "+JSON.toJSONString(instance));
			System.out.println(" instance: "+instance.getHost());
			System.out.println(" ip: "+instance.getPort());
		}
	   
	       
		

	}

}
